# crawler/tasks.py
from celery import shared_task
from django.utils import timezone
from datetime import timedelta
from django.db import transaction
from .models import LotteryData, BetRecord, UserProfile


@shared_task
def settle_bets():
    # 获取所有需要结算的期号（开奖时间超过130秒且未结算）
    threshold_time = timezone.now() - timedelta(seconds=130)

    # 使用select_for_update锁定记录防止并发
    unsettled_issues = LotteryData.objects.select_for_update().filter(
        created_at__lte=threshold_time,
        is_settled=False
    ).order_by('created_at')

    for issue in unsettled_issues:
        with transaction.atomic():
            # 处理该期所有未结算的下注
            bets = BetRecord.objects.select_related('user__profile').filter(
                issue=issue.issue_number,
                result__isnull=True
            )

            total = int(issue.sum_value)
            updates = []

            for bet in bets:
                # 判断输赢逻辑
                if bet.bet_type == 'small':
                    win = total <= 13
                elif bet.bet_type == 'big':
                    win = total >= 14
                elif bet.bet_type == 'odd':
                    win = total % 2 == 1
                elif bet.bet_type == 'even':
                    win = total % 2 == 0

                # 更新积分
                profile = bet.user.profile
                delta = bet.amount * 2 if win else -bet.amount
                profile.score += delta

                # 标记下注记录
                bet.result = win
                bet.save()
                updates.append(profile)

            # 批量更新用户积分
            UserProfile.objects.bulk_update(updates, ['score'])

            # 标记该期已结算
            issue.is_settled = True
            issue.save()